package cn.yunzhisheng.vui.assistant.tv;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

public class VuiVoiceHandleImpl implements VuiVoiceHandle {

    private VuiVoiceHandleCallback mVuiVoiceHandleCallback;
    
    private Context mContext;
    
    protected ServiceConnection mServiceConnection;

    protected IVuiVoiceCallBack mIVuiVoiceCallBack;

    protected IVoiceService mIVoiceService;


    public void setVuiVoiceHandleCallbackk(VuiVoiceHandleCallback callback) {
        mVuiVoiceHandleCallback = callback;
    }

    public VuiVoiceHandleCallback getVuiVoiceHandleCallback() {
        return mVuiVoiceHandleCallback;
    }

    public VuiVoiceHandleImpl(Context ctx) {
        mContext = ctx;
    }

    public void connectService() {
        if (mContext != null) {
            mServiceConnection = new ServiceConnection() {

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }

                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    initVoiceCallBack();
                    try {
                        mIVoiceService = IVoiceService.Stub.asInterface(service);
                        mIVoiceService.setVoiceMessageCallback(mIVuiVoiceCallBack);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            };
            mContext.bindService(new Intent(mContext, WindowService.class), mServiceConnection, Context.BIND_IMPORTANT);
        }
    }

    public void initVoiceCallBack() {
        mIVuiVoiceCallBack = new IVuiVoiceCallBack.Stub() {

            @Override
            public boolean onVoiceMessage(String msg) throws RemoteException {
                return mVuiVoiceHandleCallback.vui_voiceMessage(msg);
            }
        };
    }

    public boolean isConnectedClient() {
        if (mIVoiceService != null) {
            try {
                return mIVoiceService.hasConnectClient();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public void disconnectService() {
        if (mContext != null && mServiceConnection != null) {
            mContext.unbindService(mServiceConnection);
        }

    }
}
